package com.itheima.system.realm;

import com.alibaba.fastjson.JSON;
import com.itheima.system.pojo.Permission;
import com.itheima.system.pojo.User;
import com.itheima.system.pojo.vo.UserInfo;
import com.itheima.system.service.PermissionService;
import com.itheima.system.service.UserService;
import com.itheima.common.shiro.realm.IhrmRealm;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author qiankaofei
 * @version 1.0
 * @date 2020/11/14 13:40
 */
public class UserRealm extends IhrmRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    private static final String COADMIN="coAdmin";

    private static final String USER="user";

    private static final String SAASADMIN="saasAdmin";

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获得登录令牌UsernameAndPassword
        UsernamePasswordToken upToken=(UsernamePasswordToken) authenticationToken;
        //从登录令牌中获取用户名和密码
        String username = upToken.getUsername();
        String password=new String(upToken.getPassword());
        //根username查询用户（此处的用户即为手机号）
        User user = userService.findUserByPhone(username);
        if(user!=null && StringUtils.equals(user.getPassword(),password)){
            UserInfo info=null;
            if(StringUtils.equals(USER,user.getLevel())){
                User u = userService.findUserAndRoleAndPermission(user.getId());
                info=new UserInfo(u);
            }else{
                Map<String,Object> map=new HashMap<String,Object>(0);
                if(StringUtils.equals(COADMIN,user.getLevel())){
                    map.put("envisble","1");
                }
                List<Permission> permissionList=permissionService.findAllPermission(map);
                info=new UserInfo(user,permissionList);
            }
            //userinfo转换成json存入
            String userInfoJson= JSON.toJSONString(info);
            return new SimpleAuthenticationInfo(userInfoJson,user.getPassword(),this.getName());
        }
        //返回空，会抛出异常，显示用户名和密码不正确
        return null;
    }
}
